<template>
  <div class="app-container p-6">
    <div>
      <el-row :gutter="20">
        <!-- 用户信息卡片 -->
        <el-col :span="8">
          <el-card class="card">
            <template #header>
              <span>个人信息</span>
            </template>
            
            <div class="text-center mb-6">
              <img :src="userInfo.avatar || userInfo.avatarUrl || defaultAvatar" alt="头像" style="width:120px;height:120px;border-radius:50%;object-fit:cover;border:4px solid var(--border-light);margin-bottom:15px;" />
              <el-upload
                class="d-inline-block"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :http-request="uploadAvatarRequest"
              >
                <el-button type="primary" size="small">
                  <el-icon><Upload /></el-icon>
                  更换头像
                </el-button>
              </el-upload>
            </div>

            <div class="mb-6">
              <div class="d-flex items-center mb-3 text-sm"><span class="text-secondary" style="min-width:80px;">用户名：</span><span class="text-dark">{{ userInfo.username }}</span></div>
              <div class="d-flex items-center mb-3 text-sm"><span class="text-secondary" style="min-width:80px;">昵称：</span><span class="text-dark">{{ userInfo.nickname || '未设置' }}</span></div>
              <div class="d-flex items-center mb-3 text-sm"><span class="text-secondary" style="min-width:80px;">邮箱：</span><span class="text-dark">{{ userInfo.email || '未设置' }}</span></div>
              <div class="d-flex items-center mb-3 text-sm"><span class="text-secondary" style="min-width:80px;">手机号：</span><span class="text-dark">{{ userInfo.phone || '未设置' }}</span></div>
              <div class="d-flex items-center mb-3 text-sm"><span class="text-secondary" style="min-width:80px;">最后登录：</span><span class="text-dark">{{ formatDate(userInfo.lastLoginTime) }}</span></div>
            </div>

            <div>
              <label class="text-secondary text-sm">角色信息：</label>
              <div class="mt-2">
                <el-tag
                  v-for="role in userInfo.roles"
                  :key="role.roleId"
                  type="primary"
                  size="small"
                  class="mr-2 mb-1"
                >
                  {{ role.roleName }}
                </el-tag>
              </div>
            </div>
          </el-card>
        </el-col>

        <!-- 设置表单 -->
        <el-col :span="16">
          <el-card class="card">
            <template #header>
              <el-tabs v-model="activeTab">
                <el-tab-pane label="基本资料" name="basic" />
                <el-tab-pane label="修改密码" name="password" />
                <el-tab-pane label="系统设置" name="settings" />
              </el-tabs>
            </template>

            <!-- 基本资料 -->
            <div v-if="activeTab === 'basic'" class="pt-4">
              <el-form
                ref="basicFormRef"
                :model="basicForm"
                :rules="basicRules"
                label-width="100px"
                style="max-width: 500px"
              >
                <el-form-item label="昵称" prop="nickname">
                  <el-input v-model="basicForm.nickname" placeholder="请输入昵称" />
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="basicForm.email" placeholder="请输入邮箱" />
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                  <el-input v-model="basicForm.phone" placeholder="请输入手机号" />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="handleUpdateBasic">保存修改</el-button>
                  <el-button @click="resetBasicForm">重置</el-button>
                </el-form-item>
              </el-form>
            </div>

            <!-- 修改密码 -->
            <div v-if="activeTab === 'password'" class="pt-4">
              <el-form
                ref="passwordFormRef"
                :model="passwordForm"
                :rules="passwordRules"
                label-width="100px"
                style="max-width: 500px"
              >
                <el-form-item label="当前密码" prop="oldPassword">
                  <el-input
                    v-model="passwordForm.oldPassword"
                    type="password"
                    placeholder="请输入当前密码"
                    show-password
                  />
                </el-form-item>
                <el-form-item label="新密码" prop="newPassword">
                  <el-input
                    v-model="passwordForm.newPassword"
                    type="password"
                    placeholder="请输入新密码"
                    show-password
                  />
                </el-form-item>
                <el-form-item label="确认密码" prop="confirmPassword">
                  <el-input
                    v-model="passwordForm.confirmPassword"
                    type="password"
                    placeholder="请再次输入新密码"
                    show-password
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="handleUpdatePassword">修改密码</el-button>
                  <el-button @click="resetPasswordForm">重置</el-button>
                </el-form-item>
              </el-form>
            </div>

            <!-- 系统设置 -->
            <div v-if="activeTab === 'settings'" class="pt-4">
              <el-form label-width="120px" style="max-width: 500px">
                <el-form-item label="主题模式">
                  <el-radio-group v-model="systemSettings.theme">
                    <el-radio label="light">浅色模式</el-radio>
                    <el-radio label="dark">深色模式</el-radio>
                    <el-radio label="auto">跟随系统</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="语言">
                  <el-select v-model="systemSettings.language" style="width: 200px">
                    <el-option label="中文简体" value="zh-CN" />
                    <el-option label="English" value="en-US" />
                  </el-select>
                </el-form-item>
                <el-form-item label="侧边栏">
                  <el-switch
                    v-model="systemSettings.sidebarCollapsed"
                    active-text="折叠"
                    inactive-text="展开"
                  />
                </el-form-item>
                <el-form-item label="面包屑">
                  <el-switch v-model="systemSettings.showBreadcrumb" />
                </el-form-item>
                <el-form-item label="标签页">
                  <el-switch v-model="systemSettings.showTabs" />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="handleUpdateSettings">保存设置</el-button>
                </el-form-item>
              </el-form>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElForm } from 'element-plus'
import { Upload } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { useAppStore } from '@/stores/app'
import { formatDate } from '@/utils/date'
import defaultAvatar from '@/assets/images/default-avatar.png'
import type { UserSettings } from '@/types/system'
import request from '@/utils/request'

const userStore = useUserStore()
const appStore = useAppStore()

// 响应式数据
const activeTab = ref('basic')
const basicFormRef = ref<InstanceType<typeof ElForm>>()
const passwordFormRef = ref<InstanceType<typeof ElForm>>()

const userInfo = computed(() => userStore.userInfo || {
  avatar: '',
  avatarUrl: '',
  username: '',
  nickname: '',
  email: '',
  phone: '',
  lastLoginTime: null,
  roles: []
})

const basicForm = reactive({
  nickname: '',
  email: '',
  phone: ''
})

const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const systemSettings = reactive<UserSettings>({
  theme: 'light',
  language: 'zh-CN',
  sidebarCollapsed: false,
  showBreadcrumb: true,
  showTabs: true,
  fixedHeader: true
})

// 表单验证规则
const basicRules = {
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: Function) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入密码不一致!'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 方法
const initData = () => {
  if (userInfo.value) {
    basicForm.nickname = userInfo.value.nickname || ''
    basicForm.email = userInfo.value.email || ''
    basicForm.phone = userInfo.value.phone || ''
  }
  
  // 从应用store获取系统设置
  const appSettings = userStore.settings
  systemSettings.theme = appSettings.theme
  systemSettings.language = appSettings.language
  systemSettings.sidebarCollapsed = appSettings.sidebarCollapsed
  systemSettings.showBreadcrumb = appSettings.showBreadcrumb
  systemSettings.showTabs = appSettings.showTabs
  systemSettings.fixedHeader = appSettings.fixedHeader
}

const handleUpdateBasic = async () => {
  if (!basicFormRef.value) return
  
  await basicFormRef.value.validate((valid) => {
    if (valid) {
      // TODO: 调用API更新用户信息
      ElMessage.success('基本资料更新成功')
    }
  })
}

const resetBasicForm = () => {
  basicFormRef.value?.resetFields()
  initData()
}

const handleUpdatePassword = async () => {
  if (!passwordFormRef.value) return
  
  await passwordFormRef.value.validate((valid) => {
    if (valid) {
      // TODO: 调用API修改密码
      ElMessage.success('密码修改成功')
      resetPasswordForm()
    }
  })
}

const resetPasswordForm = () => {
  passwordFormRef.value?.resetFields()
  passwordForm.oldPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
}

const handleUpdateSettings = () => {
  // 更新用户设置
  userStore.updateSettings(systemSettings)
  
  // 更新应用设置
  appStore.setTheme(systemSettings.theme)
  appStore.setLanguage(systemSettings.language)
  
  ElMessage.success('系统设置更新成功')
}

const handleAvatarSuccess = (response: any) => {
  if (response && response.data && response.data.avatarUrl) {
    // 更新用户头像
    userStore.updateAvatar(response.data.avatarUrl)
    // 更新本地用户信息显示
    if (userInfo.value) {
      userInfo.value.avatar = response.data.avatarUrl
      userInfo.value.avatarUrl = response.data.avatarUrl
    }
    ElMessage.success('头像更换成功')
  } else {
    ElMessage.error('头像上传失败，请重试')
  }
}

const beforeAvatarUpload = (file: File) => {
  const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPGOrPNG) {
    ElMessage.error('头像图片只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('头像图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 使用封装的请求上传头像，自动携带鉴权与租户头
const uploadAvatarRequest = async (options: any) => {
  try {
    const file: File = options.file
    
    // 直接调用文件上传接口
    const formData = new FormData()
    formData.append('file', file)
    formData.append('businessType', 'avatar')
    formData.append('isPublic', 'true') // 设置为公开文件
    
    const resp = await request.post('/file/fileinfo/upload', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    })
    
    const fileId = resp.data?.id || resp.data?.data?.id
    if (fileId) {
      // 构造头像预览URL  
      const avatarUrl = `/api/file/fileinfo/preview/${fileId}`
      options.onSuccess?.({ data: { avatarUrl } })
    } else {
      options.onError?.(new Error('上传失败：未获取文件ID'))
    }
  } catch (e) {
    options.onError?.(e)
  }
}

// 生命周期
onMounted(() => {
  initData()
})
</script>

<style lang="scss" scoped></style>
